package com.lonely.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.domain.BaseEntity;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.common.utils.bean.BeanUtils;
import com.lonely.goods.domain.dto.goods.GoodsDesignInfoSubmitDTO;
import com.lonely.goods.domain.dto.goods.GoodsPartDTO;
import com.lonely.goods.domain.dto.goods.GoodsQuotationSheetPartDTO;
import com.lonely.goods.domain.entity.SysGoodsPart;
import com.lonely.goods.domain.vo.goods.CopyBomQueryVO;
import com.lonely.goods.enums.GoodsEnum;
import com.lonely.goods.mapper.SysGoodsPartMapper;
import com.lonely.goods.service.IGoodsPartMaterialService;
import com.lonely.goods.service.IGoodsPartService;
import com.lonely.goods.service.IGoodsProcessService;
import com.lonely.goods.service.IGoodsSecondProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: 黄志标
 * @date: 2025/6/25 15:42
 * @description: 商品部件接口实现
 */
@Service
public class GoodsPartServiceImpl extends ServiceImpl<SysGoodsPartMapper, SysGoodsPart> implements IGoodsPartService {

    @Autowired
    private IGoodsPartMaterialService goodsPartMaterialService;

    @Autowired
    private IGoodsSecondProcessService goodsSecondProcessService;

    @Autowired
    private IGoodsProcessService goodsProcessService;

    /**
     * 查询指定商品的报价单部件物料信息
     *
     * @param goodsId
     * @return
     */
    @Override
    public List<GoodsQuotationSheetPartDTO> queryQuotationSheetPartDetail(Long goodsId) {
        Assert.notNull(goodsId, "商品id不能为空");
        List<SysGoodsPart> goodsParts = super.list(new LambdaQueryWrapper<SysGoodsPart>()
                .eq(SysGoodsPart::getGoodsId, goodsId)
                .eq(SysGoodsPart::getStatus, CommonStatus.ENABLE.code)
        );
        if (CollUtil.isEmpty(goodsParts)) {
            return new ArrayList<>();
        }

        return goodsParts.stream().map(goodsPart -> {
            GoodsQuotationSheetPartDTO quotationSheetPartDTO = new GoodsQuotationSheetPartDTO();
            quotationSheetPartDTO.setPartId(goodsPart.getId());
            quotationSheetPartDTO.setPartLibrary(goodsPart.getPartLibrary());

            // 获取部件对应的物料信息
            quotationSheetPartDTO.setPartMaterials(this.goodsPartMaterialService.queryQuotationSheetPartMaterials(goodsPart.getId()));

            // 获取部件对应的二次工艺信息
            quotationSheetPartDTO.setPartSecondProcesses(this.goodsSecondProcessService.queryQuotationSheetPartSecondProcesses(goodsPart.getId()));

            // 获取部件对应的成衣二次工艺数据
            quotationSheetPartDTO.setPartReadyToWearSecondProcesses(this.goodsSecondProcessService.queryQuotationSheetPartReadyToWearSecondProcesses(goodsPart.getId()));

            // 获取部件对应的工序数据
            quotationSheetPartDTO.setPartProcess(this.goodsProcessService.queryQuotationSheetPartProcesses(goodsPart.getId()));
            return quotationSheetPartDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 编辑商品款信息对应的部件信息
     *
     * @param submitDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitGoodsDesignInfoParts(GoodsDesignInfoSubmitDTO submitDTO) {

        // 判断是否为套装
        if (!Objects.equals(submitDTO.getIsSuit(), 1)) {
            // 非套装，删除所有的套装类型的部件信息
            super.remove(new LambdaQueryWrapper<SysGoodsPart>()
                    .eq(SysGoodsPart::getGoodsId, submitDTO.getId())
                    .eq(SysGoodsPart::getType, GoodsEnum.GoodsPartTypeEnum.SUIT.getType())
            );

            // 判断是否存在非套装的部件类型
            int count = super.count(new LambdaQueryWrapper<SysGoodsPart>()
                    .eq(SysGoodsPart::getType, GoodsEnum.GoodsPartTypeEnum.NO_SUIT.getType())
                    .eq(SysGoodsPart::getGoodsId, submitDTO.getId())
            );
            if (count == 0) {
                // 不存在，则新增默认非套装部件
                this.initNoSuitPart(submitDTO.getId());
            }
            return;
        }

        // 是套装，则删除非套装类型的部件信息
        super.remove(new LambdaQueryWrapper<SysGoodsPart>()
                .eq(SysGoodsPart::getGoodsId, submitDTO.getId())
                .eq(SysGoodsPart::getType, GoodsEnum.GoodsPartTypeEnum.NO_SUIT.getType())
        );

        // 获取当前商品对应的部件信息
        List<SysGoodsPart> existsGoodsParts = super.list(new LambdaQueryWrapper<SysGoodsPart>()
                .eq(SysGoodsPart::getGoodsId, submitDTO.getId())
                .eq(SysGoodsPart::getStatus, CommonStatus.ENABLE.code));
        List<Long> existsPartIds = existsGoodsParts.stream().map(BaseEntity::getId).collect(Collectors.toList());
        Map<Long, SysGoodsPart> existsGoodsPartMap = existsGoodsParts.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity(), (v1, v2) -> v1));

        // 待新增的部件集合
        List<GoodsPartDTO> needAddGoodParts = submitDTO.getGoodsParts().stream().filter(x -> x.getId() == null).collect(Collectors.toList());

        // 待更新的部件集合
        List<GoodsPartDTO> needUpdateGoodPartDtos = submitDTO.getGoodsParts().stream().filter(x -> x.getId() != null).distinct().collect(Collectors.toList());
        List<Long> needUpdateGoodsPartIds = needUpdateGoodPartDtos.stream().map(GoodsPartDTO::getId).distinct().collect(Collectors.toList());

        // 待删除的部件集合
        List<Long> needDeletePartIds = existsPartIds.stream().filter(x -> !needUpdateGoodsPartIds.contains(x)).distinct().collect(Collectors.toList());

        if (CollUtil.isNotEmpty(needDeletePartIds)) {
            super.removeByIds(needDeletePartIds);
        }

        if (CollUtil.isNotEmpty(needAddGoodParts)) {
            List<SysGoodsPart> goodsParts = needAddGoodParts.stream().map(x -> {
                SysGoodsPart sysGoodsPart = new SysGoodsPart();
                sysGoodsPart.setGoodsId(submitDTO.getId());
                sysGoodsPart.setPartLibrary(x.getPartLibrary());
                sysGoodsPart.setQuantity(x.getQuantity());
                sysGoodsPart.setType(GoodsEnum.GoodsPartTypeEnum.SUIT.getType());
                sysGoodsPart.setRemark(x.getRemark());
                sysGoodsPart.setCreateBy(SecurityUtils.getUserId());
                sysGoodsPart.setUpdateBy(SecurityUtils.getUserId());
                return sysGoodsPart;
            }).collect(Collectors.toList());
            super.saveBatch(goodsParts);
        }

        if (CollUtil.isNotEmpty(needUpdateGoodPartDtos)) {
            for (GoodsPartDTO needUpdateGoodPartDto : needUpdateGoodPartDtos) {
                SysGoodsPart oldGoodsPart = existsGoodsPartMap.get(needUpdateGoodPartDto.getId());
                BeanUtils.copyProperties(needUpdateGoodPartDto, oldGoodsPart);
                super.updateById(oldGoodsPart);
            }
        }

    }

    /**
     * 复制已有bom的数据查询
     *
     * @param goodsId
     * @return
     */
    @Override
    public List<CopyBomQueryVO> copyBomDataQuery(Long goodsId) {
        Assert.notNull(goodsId, "商品id不能为空");
        List<SysGoodsPart> goodsParts = super.list(new LambdaQueryWrapper<SysGoodsPart>()
                .eq(SysGoodsPart::getGoodsId, goodsId)
                .eq(SysGoodsPart::getStatus, CommonStatus.ENABLE.code)
        );
        if (CollUtil.isEmpty(goodsParts)) {
            return new ArrayList<>();
        }

        return goodsParts.stream().map(goodsPart -> {
            CopyBomQueryVO copyBomQueryVO = new CopyBomQueryVO();
            copyBomQueryVO.setPartId(goodsPart.getId());
            copyBomQueryVO.setPartLibrary(goodsPart.getPartLibrary());
            // 获取部件对应的物料信息
            copyBomQueryVO.setPartMaterials(this.goodsPartMaterialService.queryPartMaterials(goodsPart.getId()));
            return copyBomQueryVO;
        }).collect(Collectors.toList());
    }

    /**
     * 初始化一个非套装的商品部件
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initNoSuitPart(Long id) {
        SysGoodsPart noSuitGoodsPart = new SysGoodsPart();
        noSuitGoodsPart.setGoodsId(id);
        noSuitGoodsPart.setPartLibrary("默认部件");
        noSuitGoodsPart.setQuantity(0);
        noSuitGoodsPart.setType(GoodsEnum.GoodsPartTypeEnum.NO_SUIT.getType());
        noSuitGoodsPart.setCreateBy(SecurityUtils.getUserId());
        noSuitGoodsPart.setUpdateBy(SecurityUtils.getUserId());
        super.save(noSuitGoodsPart);
    }

    /**
     * 获取指定商品的部件数
     *
     * @param goodsId
     * @return
     */
    @Override
    public Integer getMultiPiecesQuantity(Long goodsId) {
        return super.count(new LambdaQueryWrapper<SysGoodsPart>()
                .eq(SysGoodsPart::getGoodsId, goodsId)
                .eq(SysGoodsPart::getStatus, CommonStatus.ENABLE.code)
        );
    }

}
